#! -*- coding:utf-8 -*-
import os
import json
import uuid
import base64
import hashlib
import urllib
import logging
import requests
from common.utils import tz
from common.cache import redis_cache
from common.third.image import upload_data
from common.account.db import account as account_db

from django.core.management.base import BaseCommand


_LOGGER = logging.getLogger('worker')


class Command(BaseCommand):

    def _create_account(self, user_name, password, avatar):
        account = account_db.create_account({
            'is_virtual': 1,
            'user_name': user_name,
            'password': password,
            'avatar': avatar,
            'channel': 'agent'
        }, extend={
            'aid': 'agent',
            'ip': '127.0.0.1',
            'addr': 'null'
        })
        redis_cache.add_virtual_account(account.id)
        return account

    def handle(self, password, **kwargs):
        fp = open('./agents', 'r')
        count = 0
        for line in fp:
            line = line.strip()
            user_name, avatar_id = line.split('\t')
            r = urllib.urlopen(avatar_id)
            obj = r.read()
            avatar = upload_data(obj)
            print 'upload avatar %s succ' % avatar
            try:
                account = self._create_account(user_name, password, avatar)
            except Exception as e:
                print 'create account exception %s' % e
                continue
            print 'create account %s succ' % account.id
            count += 1
        print 'created %s account' % count
